package com.dongdongshop.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {


    //Shiro的过滤器工厂类
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        //给Shiro的过滤器工厂类设置安全管理器
        factoryBean.setSecurityManager(defaultWebSecurityManager);
        //设置shiro的过滤器
        Map<String, String> map = new LinkedHashMap<>();
        map.put("/seller/toLogin","anon");
        map.put("/seller/sellerLogin","anon");
        map.put("/seller/getInfoBySellerId","anon");
        map.put("/seller/toRegister","anon");
        map.put("/seller/register","anon");
        map.put("/logout","logout");
        map.put("/js/**","anon");
        map.put("/css/**","anon");
        map.put("/img/**","anon");
        map.put("/plugins/**","anon");
        map.put("/**","authc");
        factoryBean.setFilterChainDefinitionMap(map);
        factoryBean.setLoginUrl("/seller/toLogin");
//        factoryBean.setUnauthorizedUrl("/person/unauthorized");
        return factoryBean;
    }

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm loginRealm,@Autowired HashedCredentialsMatcher credentialsMatcher){
        loginRealm.setCredentialsMatcher(credentialsMatcher);
        DefaultWebSecurityManager webSecurityManager = new DefaultWebSecurityManager();
        webSecurityManager.setRealm(loginRealm);
        return webSecurityManager;
    }

    @Bean
    public HashedCredentialsMatcher credentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //指定加密方式
        credentialsMatcher.setHashAlgorithmName("MD5");
        //加密次数
        credentialsMatcher.setHashIterations(3);
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return credentialsMatcher;
    }

    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}
